﻿using System;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Data;

namespace template_dll
{
    public partial class Form12 : Form
    {
        public Form12()
        {
            InitializeComponent();
        }

        public SqlConnection conn;
        public int actionId = 0;
        public int typeActId = 0;
        public int typePrizeId = 0;

        private void Form12_Load(object sender, EventArgs e)
        {
            try
            {
                SqlStorProc.sp_params[] par = new SqlStorProc.sp_params[1];
                par[0].name = "@actionid";
                par[0].value = actionId;
                DataTable dt = new SqlStorProc().SqlProcExecWithQueryOneTable(conn, "pas_Actions_PrizeSel", 300, par);

                dataGridView1.DataSource = dt.DefaultView;
                int x = 2;
                int y = 2;
                int w = this.panel1.Width / 5 - 3;
                int h = 46;
                foreach (DataGridViewColumn col in dataGridView1.Columns)
                {

                    if (col.HeaderText != "Премия")
                    {
                        col.ReadOnly = true;
                        GroupBox gb = new GroupBox();
                        gb.Parent = this.panel1;
                        gb.Name = col.HeaderText;
                        gb.Text = col.HeaderText;
                        gb.Location = new System.Drawing.Point(x, y);
                        gb.Height = h;
                        gb.Width = w;
                        //gb.AutoSize = true;

                        ComboBox cb = new ComboBox();
                        cb.Parent = gb;
                        cb.Dock = DockStyle.Fill;
                        cb.KeyPress += comboBox1_KeyPress;
                        cb.SelectedIndexChanged += comboBox1_SelectedIndexChanged;
                        cb.KeyDown += comboBox1_KeyDown;
                        DataView view = (dataGridView1.DataSource as DataView);
                        view.Sort = "[" + col.HeaderText + "] ASC";
                        foreach (DataRow row in view.ToTable(true, col.HeaderText).Rows)
                        {
                            if (col.HeaderText != "Месяц") cb.Items.Add(row[0]);
                            else cb.Items.Add(Convert.ToDateTime(row[0]).ToString("dd.MM.yyyy"));
                        }
                        x += w + 2;
                        if (x + w + 2 > this.panel1.Width)
                        {
                            y += h + 2;
                            x = 2;
                        }
                        if (panel1.Height < y + h) panel2.Height = y + h + 2;
                    }
                    else col.ReadOnly = false;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                this.DialogResult = DialogResult.Cancel;
            }
        }

        private void comboBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            UseFilter();
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            UseFilter();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Установить премию на все видимые строки?", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                CurrencyManager cm = (CurrencyManager)dataGridView1.BindingContext[dataGridView1.DataSource];
                cm.SuspendBinding();
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    if (row.Visible)
                    {
                        if (textBox1.Text != "") row.Cells["Премия"].Value = Convert.ToDecimal(textBox1.Text);
                        else row.Cells["Премия"].Value = DBNull.Value;
                    }
                }
                cm.ResumeBinding();
            }
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '.') e.KeyChar = ',';
            if (!(Char.IsDigit(e.KeyChar)) && !((e.KeyChar == ',') && (textBox1.Text.IndexOf(",") == -1) && (textBox1.Text.Length != 0)))
            {
                if (e.KeyChar != (char)Keys.Back)
                {
                    e.Handled = true;
                }
            }
        }

        private void comboBox1_KeyDown(object sender, KeyEventArgs e)
        {
            UseFilter();
        }

        private void UseFilter()
        {
            string[] filter = new string[dataGridView1.ColumnCount - 1];
            foreach (Control c in panel1.Controls)
            {
                if (c is GroupBox)
                {
                    foreach (DataGridViewColumn col in dataGridView1.Columns)
                    {
                        if (c.Text == col.HeaderText && c.Controls[0] is ComboBox)
                        {
                            filter[col.Index] = c.Controls[0].Text;
                            break;
                        }
                    }
                }
            }
            CurrencyManager cm = (CurrencyManager)dataGridView1.BindingContext[dataGridView1.DataSource];
            cm.SuspendBinding();
            foreach (DataGridViewRow row in dataGridView1.Rows)
            {
                bool visible = true;
                for (int i = 0; i < filter.Length; i++)
                {
                    if (filter[i] != "")
                    {
                        if (row.Cells[i].Value == DBNull.Value)
                        {
                            visible = false;
                            break;
                        }
                        else
                        {
                            if (row.Cells[i].Value.ToString().IndexOf(filter[i]) < 0)
                            {
                                visible = false;
                                break;
                            }
                        }
                    }
                }
                row.Visible = visible;
            }
            cm.ResumeBinding();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                SqlStorProc.sp_params[] par = new SqlStorProc.sp_params[5];
                par[0].name = "@actionid";
                par[1].name = "@pharmcode";
                par[2].name = "@prizetypeid";
                par[3].name = "@prizesum";
                par[4].name = "@month";
                bool flag = false;
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    if (row.Cells["Премия"].Value != DBNull.Value)
                    {
                        if (row.Cells["Премия"].Value.ToString() != "")
                        {
                            par[0].value = actionId;
                            par[1].value = row.Cells["Код аптеки"].Value;
                            par[2].value = typePrizeId;
                            par[3].value = row.Cells["Премия"].Value;
                            par[4].value = Convert.ToDateTime(row.Cells["Месяц"].Value).ToString("yyyyMMdd");
                            new SqlStorProc().SqlProcExecNonQuery(conn, "pas_Actions_PrizeIns", 30, par);
                        }
                        else flag = true;
                    }
                    else flag = true;
                }
                if (!flag) MessageBox.Show("Данные сохранены");
                else MessageBox.Show("Не все данные сохранены!\nНе должно быть строк с пустыми значениями прмемий","Внимание!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
	 
        }

        private void dataGridView1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '.') e.KeyChar = ',';
            if (!(Char.IsDigit(e.KeyChar)) && !((e.KeyChar == ',') && (dataGridView1.CurrentCell.Value.ToString().IndexOf(",") == -1) && (dataGridView1.CurrentCell.Value.ToString().Length != 0)))
            {
                if (e.KeyChar != (char)Keys.Back)
                {
                    e.Handled = true;
                }
            }
        }
    }
}
